﻿using System;
using System.Threading.Tasks;
using Common.Contexts;
using Common.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Common.Filter
{
    /// <summary>
    /// 令牌验证过滤器
    /// </summary>
    public class TokenAuthenticationFilter : IAsyncActionFilter
    {
        // private readonly IUserService _userService;
        private readonly ILogger<TokenAuthenticationFilter> _logger;

        public TokenAuthenticationFilter(ILogger<TokenAuthenticationFilter> logger)
        {
            _logger = logger;
        }

        public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 从请求头获取 token
            if (!context.HttpContext.Request.Headers.TryGetValue("Authorization", out var tokenHeader)) return next();

            var token = tokenHeader.ToString().Replace("Bearer ", "");
            // _logger.LogInformation("Token: {0}", token);
            if (!string.IsNullOrEmpty(token))
                try
                {
                    if (long.TryParse(token, out var userId))
                    {
                        UserContext.UserId = userId;
                        UserContext.UserName = token;
                    }
                }
                catch (Exception ex)
                {
                    throw new TokenException("认证失效");
                }

            var result = next();
            // 请求处理完成后清理上下文
            UserContext.Clear();
            return result;
        }
    }
}